package com.code.user.service.impl;

import com.code.AZPlan.model.bo.UserVipBO;
import com.code.AZPlan.model.po.WithdrawOrder;
import com.code.commons.constants.ServerConstants;
import com.code.commons.service.impl.BaseMySqlCrudServiceImpl;
import com.code.commons.util.CollectionUtil;
import com.code.commons.util.SnowFlakeIdUtil;
import com.code.commons.util.StringUtil;
import com.code.user.api.LoginCredentialService;
import com.code.user.api.UserService;
import com.code.user.model.bo.*;
import com.code.user.model.po.*;
import com.code.user.service.helper.PasswordHelper;
import com.code.user.service.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户服务接口实现（用户基础服务层）
 *
 * @author tangyifei
 * @since 2019-5-24 15:33:14
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseMySqlCrudServiceImpl<User, String> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private LoginCredentialService loginCredentialService;

    public User getUserCredential(String id) {
        return userMapper.getUserCredential(id);
    }

    /**
     * 判断用户手机号是否已经注册
     *
     * @param userPhone 用户手机号
     * @return 手机号存在与否
     */
    public Boolean judgeUserPhoneIsExist(String userPhone) {
        String userId = userMapper.getUserIdByUserPhone(userPhone);
        if (StringUtil.isEmpty(userId)) {
            return false;
        }
        return true;
    }

    /**
     * 判断用户邮箱是否已经注册
     *
     * @param userEmail 用户邮箱
     * @return 手机号存在与否
     */
    public Boolean judgeUserEmailIsExist(String userEmail) {
        String userId = userMapper.getUserIdByUserEmail(userEmail);
        if (StringUtil.isEmpty(userId)) {
            return false;
        }
        return true;
    }

    /**
     * 通过手机号查询用户
     *
     * @param userPhone 手机号
     * @return 用户信息
     */
    @Override
    public LoginUserCredential getUserByPhone(String userPhone) {
        return userMapper.getUserByPhone(userPhone);
    }

    /**
     * 重置密码
     *
     * @param userId 用户主键
     * @param newPwd 新密码
     */
    @Override
    public void resetPwd(String userId, String newPwd) {
        userMapper.resetPwd(userId, newPwd, new Date());
    }

    /**
     * 更新用户余额信息表
     *
     * @param userCoinBalance 用户余额信息
     */
    @Override
    @Transactional(transactionManager = ServerConstants.TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int addCoinBalance(UserCoinBalance userCoinBalance) throws Exception {
        List<RechargeTranRecord> rechargeTranRecordList = userCoinBalance.getRechargeTranRecordList();
        if (CollectionUtil.isNotEmpty(rechargeTranRecordList)) {
            userMapper.insertRechargeTranRecordList(rechargeTranRecordList);
        }
        return userMapper.addCoinBalance(userCoinBalance);
    }

    /**
     * 更新用户相关的币种地址
     *
     * @param userCoinBalance 币种余额信息表
     */
    @Override
    public void updateUserCoinAddress(UserCoinBalance userCoinBalance) throws Exception {
        userMapper.updateUserCoinAddress(userCoinBalance);
    }

    /**
     * 获取用户入金通道列表
     *
     * @param userId   用户主键
     * @param coinType 币种类型
     * @return 入金通道列表
     */
    @Override
    public List<UserAZPlanChannel> getAZPlanChannelList(String userId, String coinType) {
        return userMapper.getAZPlanChannelList(userId, coinType);
    }

    /**
     * 用户充值
     *
     * @param userCoinBalance 用户余额实体对象
     * @return 用户余额实体对象
     */
    @Override
    @Transactional(transactionManager = ServerConstants.TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public UserCoinBalance recharge(UserCoinBalance userCoinBalance) {
        userMapper.updateCoinAmount(userCoinBalance);
        //插入充值流水
        Map<String, Object> rechargeFlow = Maps.newHashMapWithExpectedSize(1 << 4);
        rechargeFlow.put("id", SnowFlakeIdUtil.defaultId());
        rechargeFlow.put("userId", userCoinBalance.getUserId());
        rechargeFlow.put("flowType", ServerConstants.RECHARGE);
        rechargeFlow.put("coinType", userCoinBalance.getCoinType());
        rechargeFlow.put("address", userCoinBalance.getCoinAddress());
        rechargeFlow.put("amount", userCoinBalance.getCoinBalance());
        rechargeFlow.put("status", ServerConstants.CONFIRMED);
        rechargeFlow.put("createTime", new Date());
        rechargeFlow.put("updateTime", new Date());
        userMapper.insertRechargeFlow(rechargeFlow);
        return userMapper.getUserCoinBalance(userCoinBalance);
    }

    /**
     * 跳转邀请用户注册页面获取推荐人矿池的当前版本号和USDT钱包的账户版本号
     *
     * @param recommenderPhone 推荐人的手机号
     * @return 推荐人矿池的当前版本号和USDT钱包的账户版本号
     */
    @Override
    public UserCoinBalanceBO getUsdtVersion(String recommenderPhone) {
        String userId = userMapper.getUserIdByUserPhone(recommenderPhone);
        Integer orePoolVersion = userMapper.getOrePoolVersion(userId);
        Integer usdtCoinBalanceVersion = userMapper.getUserCoinBalanceVersion(userId, ServerConstants.USDT);
        UserCoinBalanceBO userCoinBalanceBO = UserCoinBalanceBO.builder().usdtCoinBalanceVersion(usdtCoinBalanceVersion).orePoolVersion(orePoolVersion).build();
        return userCoinBalanceBO;
    }

    /**
     * 获取用户币种余额信息
     *
     * @param userId      用户主键
     * @param coinType    币种类型
     * @param coinAddress 币种地址
     * @return 用户币种余额信息
     */
    @Override
    public UserCoinBalance getUserCoinBalance(String userId, String coinType, String coinAddress) {
        UserCoinBalance userCoinBalance = UserCoinBalance.builder().userId(userId).coinType(coinType).coinAddress(coinAddress).build();
        return userMapper.getUserCoinBalance(userCoinBalance);
    }

    /**
     * 根据用户主键和币种类型获取用户的币种地址
     *
     * @param userId   用户主键
     * @param coinType 币种类型
     * @return 币种地址
     */
    @Override
    public String getUserCoinAddressByUserId(String userId, String coinType) {
        return userMapper.getUserCoinAddressByUserId(userId, coinType);
    }

    /**
     * 通过用户主键、币种地址、币种类型获取已经同步的充值总金额
     *
     * @param userId      用户主键
     * @param coinType    币种类型
     * @param coinAddress 币种地址
     */
    @Override
    public BigDecimal getTotalRechargeAmount(String userId, String coinType, String coinAddress) {
        return userMapper.getTotalRechargeAmount(userId, coinType, coinAddress);
    }

    /**
     * 绑定token与用户手机号
     *
     * @param mobilePhone 手机号
     * @param tokenId     token主键
     */
    @Override
    public void bindingUserTokenAndUserPhone(String mobilePhone, String tokenId) {
        //查询数据库中用户手机号与token有没有绑定
        UserToken userToken = userMapper.getUserTokenByPhone(mobilePhone);
        //userToken不为空，更新tokenId
        if (null != userToken) {
            userMapper.updateUserToken(mobilePhone, tokenId, new Date());
        } else {
            UserToken userTokenForDB = UserToken.builder().phone(mobilePhone).tokenId(tokenId).build();
            userTokenForDB.setCreateTime(new Date());
            userTokenForDB.setUpdateTime(new Date());
            userMapper.insertUserToken(userTokenForDB);
        }
    }

    /**
     * 根据用户手机号获取用户登录token
     *
     * @param mobilePhone 用户手机号
     * @return 用户登录token
     */
    @Override
    public String getUserTokenByUserPhone(String mobilePhone) {
        //查询数据库中用户手机号与token有没有绑定
        return userMapper.getUserTokenByPhone(mobilePhone).getTokenId();
    }

    /**
     * 提交用户认证
     *
     * @param userCertification 用户认证对象
     * @return 影响的行数
     */
    @Override
    public int addUserCertification(UserCertification userCertification) {
        //如果用户认证状态不成功，则进行修改
        UserCertification userCertificationDB = userMapper.getUserCertificationByUserId(userCertification.getUserId());
        if (null != userCertificationDB) {
            userCertification.setUpdateTime(new Date());
            return userMapper.updateUserCertification(userCertification);
        } else {
            userCertification.setId(SnowFlakeIdUtil.defaultId());
            userCertification.setAuthTime(new Date());
            userCertification.setCreateTime(new Date());
            userCertification.setUpdateTime(new Date());
            return userMapper.addUserCertification(userCertification);
        }
    }

    /**
     * 获取用户认证详情
     *
     * @param userId 用户主键
     * @return 用户认证详情
     */
    @Override
    public UserCertification getUserCertificationByUserId(String userId) {
        return userMapper.getUserCertificationByUserId(userId);
    }

    /**
     * 通过证件号码获取该证件号认证的用户个数
     *
     * @param certificationNumber 用户主键
     * @return 证件号认证的用户个数
     */
    @Override
    public int getUserCertificationCountByCertificationNumber(String certificationNumber) {
        return userMapper.getUserCertificationCountByCertificationNumber(certificationNumber);
    }

    /**
     * 获取用户认证列表
     *
     * @param userCertificationBO 用户认证查询对象
     * @return 用户认证列表
     */
    @Override
    public UserCertificationBO getUserCertificationList(UserCertificationBO userCertificationBO) {
        Integer page = userCertificationBO.getPage();
        Integer pageSize = userCertificationBO.getPageSize();
        UserCertificationBO userCertificationBOResult = UserCertificationBO.builder().page(page).build();
        if (null != page && null != pageSize) {
            PageHelper.startPage(page, pageSize);
            List<UserCertification> userCertificationList = userMapper.getUserCertificationList(userCertificationBO);
            userCertificationBOResult.setUserCertificationList(userCertificationList);
            userCertificationBOResult.setTotal(new PageInfo<>(userCertificationList).getTotal());
        } else {
            List<UserCertification> userCertificationList = userMapper.getUserCertificationList(userCertificationBO);
            userCertificationBOResult.setUserCertificationList(userCertificationList);
        }
        return userCertificationBOResult;
    }

    /**
     * 更新用户认证信息
     *
     * @param userCertification 用户认证对象
     * @return 影响的行数
     */
    @Override
    public int updateUserCertification(UserCertification userCertification) {
        UserCertification userCertificationDB = userMapper.getUserCertificationByUserId(userCertification.getUserId());
        if (null != userCertificationDB) {
            userCertification.setAuthTime(new Date());
            userCertification.setUpdateTime(new Date());
            return userMapper.updateUserCertification(userCertification);
        }
        return 0;
    }

    /**
     * 更新系统维护开关
     *
     * @param systemSettingBO 系统维护业务对象
     * @return 影响的行数
     */
    @Override
    public int updateSystemSetting(SystemSettingBO systemSettingBO) {
        SystemSettingBO systemSettingDB = userMapper.getSystemSettingBOBySystemKey(ServerConstants.SYSTEM_PROTECT);
        if (null != systemSettingDB) {
            systemSettingBO.setUpdateTime(new Date());
            return userMapper.updateSystemProtect(systemSettingBO);
        }
        return 0;
    }

    /**
     * 获取系统信息
     *
     * @param systemKey 系统相关的key
     * @return 系统信息
     */
    @Override
    public SystemSettingBO getSystemSettingBySystemKey(String systemKey) {
        return userMapper.getSystemSettingBOBySystemKey(systemKey);
    }

    /**
     * 用户充值
     *
     * @param rechargeTranRecord 用户充值实体对象
     * @return 影响的行数
     */
    @Override
    @Transactional(transactionManager = ServerConstants.TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int recharge(RechargeTranRecord rechargeTranRecord) {
        Integer rechargeType = rechargeTranRecord.getRechargeType();
        int count = 0;
        //充值
        if (1 == rechargeType) {
            count = userMapper.rechargeCoinBalance(rechargeTranRecord);
        }
        //扣除
        if (4 == rechargeType) {
            count = userMapper.reduceCoinBalance(rechargeTranRecord);
        }
        if (count > 0) {
            rechargeTranRecord.setId(SnowFlakeIdUtil.defaultId());
            rechargeTranRecord.setTxId(UUID.randomUUID().toString());
            rechargeTranRecord.setTxTime(new Date());
            rechargeTranRecord.setCreateTime(new Date());
            rechargeTranRecord.setConfirmations(0);
            count += userMapper.insertRechargeTranRecord(rechargeTranRecord);
        }
        return count;
    }

    /**
     * 获取某一个用户钱包列表
     *
     * @param userId 用户主键
     * @return 用户钱包列表
     */
    @Override
    public List<UserCoinBalance> getUserCoinBalanceList(String userId) {
        return userMapper.getUserCoinBalanceList(userId);
    }

    /**
     * 通过用户手机号的部分信息模糊查询用户手机
     *
     * @param phone 用户手机号
     * @return 用户手机号列表
     */
    @Override
    public PhoneBO getUserPhones(String phone, Integer page, Integer pageSize) {
        PhoneBO phoneBO = new PhoneBO();
        if (null != page && null != pageSize) {
            PageHelper.startPage(page, pageSize);
            List<String> phoneList = userMapper.getUserPhones(phone);
            phoneBO.setPhoneList(phoneList);
            phoneBO.setTotal(new PageInfo<>(phoneList).getTotal());
        } else {
            List<String> phoneList = userMapper.getUserPhones(phone);
            phoneBO.setPhoneList(phoneList);
        }
        return phoneBO;
    }

    /**
     * 禁止或者取消用户的相关的操作
     *
     * @param userOperateAuth 用户操作权限PO及持久层对象
     * @return 影响的行数
     */
    @Override
    public int setUserOperate(UserOperateAuth userOperateAuth) {
        Assert.notNull(userOperateAuth, "userOperateAuth is not null");
        Integer operateType = userOperateAuth.getOperateType();
        int count = 0;
        if (1 == operateType) {
            UserOperateAuth userOperateAuthDB = userMapper.getUserOperateAuthByUserIdAndOperateCode(userOperateAuth.getUserId(), ServerConstants.WITHDRAW_CODE);
            if (null != userOperateAuthDB) {
                userOperateAuth.setOperateCode(ServerConstants.WITHDRAW_CODE);
                userOperateAuth.setUpdateTime(Date.from(Instant.now()));
                count = userMapper.updateUserOperateAuth(userOperateAuth);
            } else {
                userOperateAuth.setId(SnowFlakeIdUtil.defaultId());
                userOperateAuth.setOperateCode(ServerConstants.WITHDRAW_CODE);
                userOperateAuth.setCreateTime(Date.from(Instant.now()));
                count = userMapper.addUserOperateAuth(userOperateAuth);
            }

        }
        if (2 == operateType) {
            UserOperateAuth userOperateAuthDB = userMapper.getUserOperateAuthByUserIdAndOperateCode(userOperateAuth.getUserId(), ServerConstants.INSITE_TRANSFER_IN_CODE);
            if (null != userOperateAuthDB) {
                userOperateAuth.setOperateCode(ServerConstants.INSITE_TRANSFER_IN_CODE);
                userOperateAuth.setUpdateTime(Date.from(Instant.now()));
                count = userMapper.updateUserOperateAuth(userOperateAuth);
            } else {
                userOperateAuth.setId(SnowFlakeIdUtil.defaultId());
                userOperateAuth.setOperateCode(ServerConstants.INSITE_TRANSFER_IN_CODE);
                userOperateAuth.setCreateTime(Date.from(Instant.now()));
                count = userMapper.addUserOperateAuth(userOperateAuth);
            }

        }
        return count;
    }

    /**
     * 根据用户主键和操作码查询用户的操作权限
     *
     * @param userId      用户主键
     * @param operateCode 操作码
     * @return UserOperateAuth 用户操作权限PO及持久层对象
     */
    @Override
    public UserOperateAuth getUserOperateAuthByUserIdAndOperateCode(String userId, String operateCode) {
        return userMapper.getUserOperateAuthByUserIdAndOperateCode(userId, operateCode);
    }

    /**
     * 根据手机号获取tokenId
     *
     * @param userVipBOS userVip对象
     * @return token对象
     */
    @Override
    public List<UserToken> getTokenList(List<UserVipBO> userVipBOS) {
        return userMapper.getTokenList(userVipBOS);
    }

    /**
     * 通过币种类型获取钱包相关币种信息列表
     *
     * @param coinType 币种类型
     * @return 用户钱包相关币种信息列表
     */
    @Override
    public List<UserCoinBalance> getUserWalletList(String coinType) {
        return userMapper.getUserWalletList(coinType);
    }

    /**
     * 扣减用户钱包金额
     *
     * @param userCoinBalance 用户钱包余额对象
     * @return 提币订单列表
     */
    @Override
    @Transactional(transactionManager = ServerConstants.TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public int reduceUserCoinBalance(UserCoinBalance userCoinBalance) {
//        UserCoinBalance userCoinBalanceDB = userMapper.getUserCoinBalance(userCoinBalance);
        int count = 0;
//        if (null != userCoinBalanceDB) {
//            count = userMapper.reduceUserCoinBalance(userCoinBalance);
//        }
        if (StringUtil.isNotEmpty(userCoinBalance.getWithdrawOrderId())) {
            WithdrawOrder withdrawOrderDB = userMapper.getWithdrawOrder(userCoinBalance.getWithdrawOrderId());
            if (null != withdrawOrderDB) {
                count += userMapper.updateWithdrawOrderCheckState(userCoinBalance.getWithdrawOrderId(), new Date());
            }
        }
        return count;
    }

    /**
     * 根据用户主键获取推荐人的直推用户列表
     *
     * @param userId          用户主键
     * @param entryMoneyState 有无入金
     * @param page            当前页
     * @param pageSize        每页的大小
     * @return 推荐人的直推用户列表
     */
    @Override
    public Map<String, Object> getDirectRecommends(String userId, Integer entryMoneyState, Integer page, Integer pageSize) {
        long start = System.currentTimeMillis();
        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(1 << 5);
        int total;
        if (null != page && null != pageSize) {
            int startNum = (page - 1) * pageSize;
            PageHelper.startPage(page, pageSize);
            //获取直接推荐人列表
            List<UserRecommenderBO> userRecommends = userMapper.getRecommendsByUserId(userId, entryMoneyState).stream()
                    .map(recommend -> {
                        recommend.setNum(recommend.getNum() + startNum);
                        return recommend;
                    }).collect(Collectors.toList());
            resultMap.put("userRecommends", userRecommends);
            total = userMapper.getRecommendsCountByUserId(userId, entryMoneyState);
        } else {
            List<UserRecommenderBO> userRecommends = userMapper.getRecommendsByUserId(userId, entryMoneyState);
            resultMap.put("userRecommends", userRecommends);
            total = userRecommends.size();
        }
        resultMap.put("total", total);
        log.info("getDirectRecommends query cost time:{}", System.currentTimeMillis() - start);
        return resultMap;
    }

    /**
     * 注册用户
     *
     * @param registerUser 注册用户对象
     * @return 影响的行数
     */
    @Override
    @Transactional(transactionManager = ServerConstants.TRANSACTION_MANAGER, rollbackFor = Exception.class)
    public User registerUser(RegisterUser registerUser) {
        User user = registerUser.getUser();
        if (null != user) {
            //注册用户
            String userId = SnowFlakeIdUtil.defaultId();
            UserRecommender userRecommender = registerUser.getUserRecommender();
            if (null != userRecommender) {
                String recommenderPhone = userRecommender.getRecommenderPhone();
                if (StringUtil.isNotEmpty(recommenderPhone)) {
                    userRecommender.setId(SnowFlakeIdUtil.defaultId());
                    LoginUserCredential recommendUser = userMapper.getUserByPhone(recommenderPhone);
                    String recommenderId = recommendUser.getId();
                    userRecommender.setRecommenderId(recommenderId);
                    userRecommender.setRecommenderUserId(userId);
                    userRecommender.setRecommenderUserPhone(user.getPhone());
//                    userRecommender.setRecommenderIncome(new BigDecimal("100"));
                    userRecommender.setRecommenderIncomeState(0);
                    userRecommender.setCreateTime(new Date());
                    userRecommender.setUpdateTime(new Date());
                    userRecommender.setRecommendState(0);
                    userMapper.insertUserRecommender(userRecommender);
                    //获取内存树
//                    AccountTree tree = (AccountTree) ServerConstants.treeMap.get(ServerConstants.RECOMMENG_TREE);
//                    if (null != tree) {
//                        try {
////                            tree.setAccountInfo(userId, BigDecimal.ZERO, BigDecimal.ZERO, null, 0, recommenderId);
//                            tree.addNewAccount(userId, recommenderId, BigDecimal.ZERO, BigDecimal.ZERO);
//                        } catch (Exception e) {
//                            log.error("发生错误：【{}】", e);
//                        }
//                    }


                    //推荐人的矿池大小
//                    BigDecimal orePool = recommendUser.getOrePool();
                    //推荐人的矿池不为空说明推荐人进行了投资，那么推荐人才能获取收益
//                    if (null != orePool && orePool.compareTo(BigDecimal.ZERO) != 0) {
//                        //推荐人的矿池状态，看当前的推荐人有没有复投等状态
//                        Integer doubleThrowState = recommendUser.getDoubleThrowState();
//                        //获取当前推荐人已经推荐第几个人了，即被推荐人的在推荐人推荐的名单里的推荐顺序
//                        Integer recommenderIndex = userMapper.getRecommenderIndex(recommenderPhone);
//                        //推荐人当前推荐的第一个人
//                        if (null == recommenderIndex) {
//                            userRecommender.setRecommenderIndex(1);
//                            //第二种情况：推荐人已入金，但是推荐人矿池大小小于被推荐人入金后的获取的10%的额度，那么就把推荐人的剩余矿池大小直接转入到推荐人的钱包中
//                            if (orePool.compareTo(new BigDecimal("100")) >= 0) {
//                                userRecommender.setRecommenderId(recommenderId);
//                                userRecommender.setRecommenderUserId(userId);
//                                userRecommender.setRecommenderUserPhone(user.getPhone());
//                                userRecommender.setRecommenderIncome(new BigDecimal("100"));
//                                userRecommender.setRecommenderIncomeState(0);
//                                userRecommender.setCreateTime(new Date());
//                                userRecommender.setUpdateTime(new Date());
//                                userRecommender.setRecommendState(0);
//                                userMapper.insertUserRecommender(userRecommender);
//                            }
//                        } else {
//                            recommenderIndex = 1 + recommenderIndex;
//                            userRecommender.setRecommenderIndex(recommenderIndex);
//                            if (recommenderIndex <= 6) {
//
//                                //推荐第二个人或者推荐第五个人
//                                if (recommenderIndex == 2 || recommenderIndex == 5) {
//                                    if (orePool.compareTo(new BigDecimal("300")) >= 0) {
//                                        //查看是否为复投
//                                        if (ServerConstants.DOUBLE_THROW == doubleThrowState) {
//                                            userRecommender.setRecommenderId(recommenderId);
//                                            userRecommender.setRecommenderUserId(userId);
//                                            userRecommender.setRecommenderUserPhone(user.getPhone());
//                                            userRecommender.setRecommenderIncome(new BigDecimal("100"));
//                                            userRecommender.setRecommenderIncomeState(0);
//                                            userRecommender.setCreateTime(new Date());
//                                            userRecommender.setUpdateTime(new Date());
//                                            userRecommender.setRecommendState(0);
//                                            userMapper.insertUserRecommender(userRecommender);
//                                        } else {
//                                            //不是复投
//                                            userRecommender.setRecommenderId(recommenderId);
//                                            userRecommender.setRecommenderUserId(userId);
//                                            userRecommender.setRecommenderUserPhone(user.getPhone());
//                                            userRecommender.setRecommenderIncome(new BigDecimal("300"));
//                                            userRecommender.setRecommenderIncomeState(0);
//                                            userRecommender.setCreateTime(new Date());
//                                            userRecommender.setUpdateTime(new Date());
//                                            userRecommender.setRecommendState(0);
//                                            userMapper.insertUserRecommender(userRecommender);
//                                        }
//                                    }
//                                }
//                                //推荐第三个人或者推荐第六个人
//                                if (recommenderIndex == 3 || recommenderIndex == 6) {
//                                    if (orePool.compareTo(new BigDecimal("600")) >= 0) {
//                                        //查看是否为复投
//                                        if (ServerConstants.DOUBLE_THROW == doubleThrowState) {
//                                            userRecommender.setRecommenderId(recommenderId);
//                                            userRecommender.setRecommenderUserId(userId);
//                                            userRecommender.setRecommenderUserPhone(user.getPhone());
//                                            userRecommender.setRecommenderIncome(new BigDecimal("100"));
//                                            userRecommender.setRecommenderIncomeState(0);
//                                            userRecommender.setCreateTime(new Date());
//                                            userRecommender.setUpdateTime(new Date());
//                                            userRecommender.setRecommendState(0);
//                                            userMapper.insertUserRecommender(userRecommender);
//                                        } else {
//                                            //不是复投
//                                            userRecommender.setRecommenderId(recommenderId);
//                                            userRecommender.setRecommenderUserId(userId);
//                                            userRecommender.setRecommenderUserPhone(user.getPhone());
//                                            userRecommender.setRecommenderIncome(new BigDecimal("600"));
//                                            userRecommender.setRecommenderIncomeState(0);
//                                            userRecommender.setCreateTime(new Date());
//                                            userRecommender.setUpdateTime(new Date());
//                                            userRecommender.setRecommendState(0);
//                                            userMapper.insertUserRecommender(userRecommender);
//                                        }
//                                    }
//                                }
//                                //推荐第四个人
//                                if (recommenderIndex == 4) {
//                                    if (orePool.compareTo(new BigDecimal("100")) >= 0) {
//                                        userRecommender.setRecommenderId(recommenderId);
//                                        userRecommender.setRecommenderUserId(userId);
//                                        userRecommender.setRecommenderUserPhone(user.getPhone());
//                                        userRecommender.setRecommenderIncome(new BigDecimal("100"));
//                                        userRecommender.setRecommenderIncomeState(0);
//                                        userRecommender.setCreateTime(new Date());
//                                        userRecommender.setUpdateTime(new Date());
//                                        userRecommender.setRecommendState(0);
//                                        userMapper.insertUserRecommender(userRecommender);
//                                    }
//                                }
//                            } else {
//                                //查看是否为复投
//                                if (ServerConstants.DOUBLE_THROW == doubleThrowState) {
//                                    userRecommender.setRecommenderId(recommenderId);
//                                    userRecommender.setRecommenderUserId(userId);
//                                    userRecommender.setRecommenderUserPhone(user.getPhone());
//                                    userRecommender.setRecommenderIncome(new BigDecimal("100"));
//                                    userRecommender.setRecommenderIncomeState(0);
//                                    userRecommender.setCreateTime(new Date());
//                                    userRecommender.setUpdateTime(new Date());
//                                    userRecommender.setRecommendState(0);
//                                    userMapper.insertUserRecommender(userRecommender);
//                                }
//                            }
//
//                        }
//                    } else {
//                        //如果推荐人没有投资（入金）或者推荐人的矿池为0（已释放完），那么推荐人不可能有收益产生，必须重新入金（复投）
//                        //推荐人的矿池为0，不管推荐第几个人，总是不够减去被推荐人的收益（10%、30%、60%）
//                        log.info("推荐人没有投资，没有收益产生！");
//                    }
                }
            }
            user.setUpdateTime(new Date());
            user.setCreateTime(new Date());
            user.setId(userId);
            crudMapper.insert(user);
            //向用户的相关币种余额信息表插入默认信息
            List<Map<String, Object>> userCoinBalanceMaps = Lists.newArrayListWithCapacity(1 << 3);
            Map<String, Object> userCoinBalanceMap1 = Maps.newHashMapWithExpectedSize(1 << 5);
            userCoinBalanceMap1.put("userId", userId);
            userCoinBalanceMap1.put("coinType", ServerConstants.XWC);
            userCoinBalanceMap1.put("coinBalance", 0);
            userCoinBalanceMap1.put("version", 0);
            userCoinBalanceMap1.put("createTime", new Date());
            userCoinBalanceMap1.put("updateTime", new Date());
            userCoinBalanceMaps.add(userCoinBalanceMap1);
            Map<String, Object> userCoinBalanceMap2 = Maps.newHashMapWithExpectedSize(1 << 5);
            userCoinBalanceMap2.put("userId", userId);
            userCoinBalanceMap2.put("coinType", ServerConstants.BTC);
            userCoinBalanceMap2.put("coinBalance", 0);
            userCoinBalanceMap2.put("version", 0);
            userCoinBalanceMap2.put("createTime", new Date());
            userCoinBalanceMap2.put("updateTime", new Date());
            userCoinBalanceMaps.add(userCoinBalanceMap2);
            Map<String, Object> userCoinBalanceMap3 = Maps.newHashMapWithExpectedSize(1 << 5);
            userCoinBalanceMap3.put("userId", userId);
            userCoinBalanceMap3.put("coinType", ServerConstants.USDT);
            userCoinBalanceMap3.put("coinBalance", 0);
            userCoinBalanceMap3.put("version", 0);
            userCoinBalanceMap3.put("createTime", new Date());
            userCoinBalanceMap3.put("updateTime", new Date());
            userCoinBalanceMaps.add(userCoinBalanceMap3);
            userMapper.addUserCoinBalanceDefaultInfo(userCoinBalanceMaps);
            //增加用户入金通道
            List<UserAZPlanChannel> userAZPlanChannelList = Lists.newArrayListWithCapacity(1 << 3);
            UserAZPlanChannel userAZPlanChannelOne = UserAZPlanChannel.builder().userId(userId).azPlanChannel("1000").lockStatus(0).build();
            userAZPlanChannelOne.setCreateTime(new Date());
            userAZPlanChannelOne.setUpdateTime(new Date());
            userAZPlanChannelList.add(userAZPlanChannelOne);
            UserAZPlanChannel userAZPlanChannelTwo = UserAZPlanChannel.builder().userId(userId).azPlanChannel("3000").lockStatus(1).build();
            userAZPlanChannelTwo.setCreateTime(new Date());
            userAZPlanChannelTwo.setUpdateTime(new Date());
            userAZPlanChannelList.add(userAZPlanChannelTwo);
            UserAZPlanChannel userAZPlanChannelThree = UserAZPlanChannel.builder().userId(userId).azPlanChannel("5000").lockStatus(1).build();
            userAZPlanChannelThree.setCreateTime(new Date());
            userAZPlanChannelThree.setUpdateTime(new Date());
            userAZPlanChannelList.add(userAZPlanChannelThree);
            userMapper.insertUserAZPlanChannelList(userAZPlanChannelList);
            //初始化用户的AZ计划余额表
            Map<String, Object> azBalanceMap = Maps.newHashMapWithExpectedSize(1 << 5);
            azBalanceMap.put("id", SnowFlakeIdUtil.defaultId());
            azBalanceMap.put("userId", userId);
            azBalanceMap.put("userParentId", 0);
            azBalanceMap.put("orePool", 0);
            azBalanceMap.put("totalEntryMoney", 0);
            azBalanceMap.put("totalStaticIncomeAmount", 0);
            azBalanceMap.put("totalDynamicIncomeAmount", 0);
            azBalanceMap.put("azPlanStatus", 0);
            azBalanceMap.put("doubleThrowState", 0);
            azBalanceMap.put("userVipLevel", "V0");
            azBalanceMap.put("userLevel", "1");
            azBalanceMap.put("version", 0);
            azBalanceMap.put("createTime", new Date());
            azBalanceMap.put("updateTime", new Date());
            userMapper.insertAZPlanBalance(azBalanceMap);
            //初始化资金划转记录表
            List<Map<String, Object>> azMoneyTransferMaps = Lists.newArrayListWithCapacity(1 << 3);
            Map<String, Object> azMoneyTransferMap1 = Maps.newHashMapWithExpectedSize(1 << 5);
            azMoneyTransferMap1.put("id", SnowFlakeIdUtil.defaultId());
            azMoneyTransferMap1.put("userId", userId);
            azMoneyTransferMap1.put("amount", 0);
            azMoneyTransferMap1.put("transferType", 1);
            azMoneyTransferMap1.put("coinType", ServerConstants.XWC);
            azMoneyTransferMap1.put("version", 0);
            azMoneyTransferMap1.put("createTime", new Date());
            azMoneyTransferMap1.put("updateTime", new Date());
            azMoneyTransferMaps.add(azMoneyTransferMap1);
            Map<String, Object> azMoneyTransferMap2 = Maps.newHashMapWithExpectedSize(1 << 5);
            azMoneyTransferMap2.put("id", SnowFlakeIdUtil.defaultId());
            azMoneyTransferMap2.put("userId", userId);
            azMoneyTransferMap2.put("amount", 0);
            azMoneyTransferMap2.put("transferType", 2);
            azMoneyTransferMap2.put("coinType", ServerConstants.XWC);
            azMoneyTransferMap2.put("version", 0);
            azMoneyTransferMap2.put("createTime", new Date());
            azMoneyTransferMap2.put("updateTime", new Date());
            azMoneyTransferMaps.add(azMoneyTransferMap2);
            Map<String, Object> azMoneyTransferMap3 = Maps.newHashMapWithExpectedSize(1 << 5);
            azMoneyTransferMap3.put("id", SnowFlakeIdUtil.defaultId());
            azMoneyTransferMap3.put("userId", userId);
            azMoneyTransferMap3.put("amount", 0);
            azMoneyTransferMap3.put("transferType", 2);
            azMoneyTransferMap3.put("coinType", ServerConstants.BTC);
            azMoneyTransferMap3.put("version", 0);
            azMoneyTransferMap3.put("createTime", new Date());
            azMoneyTransferMap3.put("updateTime", new Date());
            azMoneyTransferMaps.add(azMoneyTransferMap3);
            userMapper.insertAZPlanMoneyTransferList(azMoneyTransferMaps);
            //初始化AZ钱包信息
            List<Map<String, Object>> azWalletMaps = Lists.newArrayListWithCapacity(1 << 3);
            Map<String, Object> azWalletMap1 = Maps.newHashMapWithExpectedSize(1 << 5);
            azWalletMap1.put("id", SnowFlakeIdUtil.defaultId());
            azWalletMap1.put("userId", userId);
            azWalletMap1.put("coinType", ServerConstants.XWC);
            azWalletMap1.put("amount", 0);
            azWalletMap1.put("version", 0);
            azWalletMap1.put("createTime", new Date());
            azWalletMap1.put("updateTime", new Date());
            azWalletMaps.add(azWalletMap1);
            Map<String, Object> azWalletMap2 = Maps.newHashMapWithExpectedSize(1 << 5);
            azWalletMap2.put("id", SnowFlakeIdUtil.defaultId());
            azWalletMap2.put("userId", userId);
            azWalletMap2.put("coinType", ServerConstants.BTC);
            azWalletMap2.put("amount", 0);
            azWalletMap2.put("version", 0);
            azWalletMap2.put("createTime", new Date());
            azWalletMap2.put("updateTime", new Date());
            azWalletMaps.add(azWalletMap2);
            userMapper.insertAZWalletList(azWalletMaps);
            //注册用户的凭证信息
            LoginCredential loginCredential = registerUser.getLoginCredential();
            if (null != loginCredential) {
                loginCredential.setUserId(userId);
                loginCredential.setCreateTime(new Date());
                loginCredential.setUpdateTime(new Date());
                //生成随机盐值
                String salt = PasswordHelper.generateRandomSalt();
                loginCredential.setRandomSalt(salt);
                //获取客户端的加密密码(一般可能为md5加密传输)
                String pwd = loginCredential.getPwd();
                loginCredential.setPwd(PasswordHelper.encodeBySalt(pwd, salt));
                loginCredential.setType(LoginCredential.LoginCredentialTypeEnum.CUSTOM.name());
                loginCredential.setTranPwdIsNotSet(1);
                loginCredentialService.insert(loginCredential);
            }
        }
        return user;
    }

}
